package com.superyee.commonlib.videoplayer.controller;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.dueeeke.videoplayer.controller.ControlWrapper;
import com.dueeeke.videoplayer.controller.IControlComponent;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.util.L;
import com.dueeeke.videoplayer.util.PlayerUtils;
import com.superyee.commonlib.R;

public class TikTokView extends FrameLayout implements IControlComponent,
        GestureDetector.OnGestureListener, View.OnTouchListener {

    /**
     * 监听左滑打开activity事件
     */
    private OnClickListener mNextPageListener;
    protected ControlWrapper mControlWrapper;
    private ProgressBar mBottomProgress;
    private ImageView mPlayButton;
    private ImageView thumb;
    private int mScaledTouchSlop;
    private int mStartX, mStartY;
    protected GestureDetector mGestureDetector;
    private int mDistanceX;

    public TikTokView(@NonNull Context context) {
        super(context);
    }

    public TikTokView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TikTokView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public void enableGesture(boolean enableGesture) {
        if (enableGesture) {
            mDistanceX = getResources().getDimensionPixelOffset(R.dimen.dp_100);
            mGestureDetector = new GestureDetector(getContext(), this);
            setOnClickListener(null);
            setOnTouchListener(this);
        } else {
            if (hasOnClickListeners())
                return;
            setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    mControlWrapper.togglePlay();
                }
            });
        }
    }

    {
        LayoutInflater.from(getContext()).inflate(R.layout.comm_layout_tiktok_controller, this, true);
        thumb = findViewById(R.id.iv_thumb);
        mPlayButton = findViewById(R.id.play_btn);
        mBottomProgress = findViewById(R.id.progressBar);
        mScaledTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mControlWrapper.togglePlay();
            }
        });
    }


    public ImageView getThumb() {
        return thumb;
    }

    /**
     * 监听屏幕左滑打开新的activity
     *
     * @param listener
     */
    public void setOnNextPageListener(OnClickListener listener) {
        this.mNextPageListener = listener;
    }

    @Override
    public void attach(@NonNull ControlWrapper controlWrapper) {
        mControlWrapper = controlWrapper;
    }

    /**
     * 解决点击和VerticalViewPager滑动冲突问题
     */
    public boolean onTouchEvent1(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mStartX = (int) event.getX();
                mStartY = (int) event.getY();
                return true;
            case MotionEvent.ACTION_UP:
                int endX = (int) event.getX();
                int endY = (int) event.getY();
                if (Math.abs(endX - mStartX) < mScaledTouchSlop
                        && Math.abs(endY - mStartY) < mScaledTouchSlop) {
                    mControlWrapper.togglePlay();
                }
                break;
        }
        return false;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return mGestureDetector.onTouchEvent(motionEvent);
    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return true;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        mControlWrapper.togglePlay();
        return true;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        if (distanceX > 0 && (distanceX > mDistanceX / 10 || distanceX > Math.abs(distanceY))) {
            getParent().requestDisallowInterceptTouchEvent(true);
            return true;
        } else {
            getParent().requestDisallowInterceptTouchEvent(false);
        }
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }


    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2,
                           float velocityX, float velocityY) {
        // 判断纵向滑动是否过大，过大的话不允许切换界面
        if (Math.abs(e2.getRawY() - e1.getRawY()) > mDistanceX * 1.5) {
            return false;
        }
        // 判断滑动是否龟速，如果速度过慢也不允许滑动到另一页
//        if (Math.abs(velocityX) < mDistanceX / 2.5) {
//            return false;
//        }
        // 向右滑动,上一页
//        if (e2.getRawX() - e1.getRawX() > mDistanceX) {
//            return true;
//        }
        // 向左滑动,下一页
        if (e1.getRawX() - e2.getRawX() > mDistanceX) {
            if (mNextPageListener != null) {
                mNextPageListener.onClick(this);
            }
            return true;
        }
        return false;
    }

    @Override
    public View getView() {
        return this;
    }

    @Override
    public void onVisibilityChanged(boolean isVisible, Animation anim) {

    }


    @Override
    public void onPlayStateChanged(int playState) {
        switch (playState) {
            case VideoView.STATE_IDLE:
                thumb.setVisibility(VISIBLE);
                mBottomProgress.setProgress(0);
                mBottomProgress.setSecondaryProgress(0);
                break;
            case VideoView.STATE_PREPARING:
            case VideoView.STATE_PREPARED:
                mBottomProgress.setVisibility(VISIBLE);
                break;
            case VideoView.STATE_PLAYING:
                thumb.setVisibility(GONE);
                mPlayButton.setVisibility(GONE);
                //开始刷新进度
                mControlWrapper.startProgress();
                break;
            case VideoView.STATE_PAUSED:
                thumb.setVisibility(GONE);
                mPlayButton.setVisibility(VISIBLE);
                break;
            case VideoView.STATE_BUFFERING:
            case VideoView.STATE_BUFFERED:
                mPlayButton.setSelected(mControlWrapper.isPlaying());
                break;
            case VideoView.STATE_ERROR:
                L.e("STATE_ERROR " + hashCode());
                Toast.makeText(getContext(), R.string.dkplayer_error_message, Toast.LENGTH_SHORT).show();
                break;
            case VideoView.STATE_PLAYBACK_COMPLETED:
                mBottomProgress.setVisibility(GONE);
                mBottomProgress.setProgress(0);
                mBottomProgress.setSecondaryProgress(0);
                break;
        }
    }

    @Override
    public void onPlayerStateChanged(int playerState) {
        Activity activity = PlayerUtils.scanForActivity(getContext());
        if (activity != null && mControlWrapper.hasCutout()) {
            int orientation = activity.getRequestedOrientation();
            int cutoutHeight = mControlWrapper.getCutoutHeight();
            if (orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                mBottomProgress.setPadding(0, 0, 0, 0);
            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                mBottomProgress.setPadding(cutoutHeight, 0, 0, 0);
            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
                mBottomProgress.setPadding(0, 0, cutoutHeight, 0);
            }
        }
    }

    @Override
    public void setProgress(int duration, int position) {

        if (mBottomProgress != null) {
            if (duration > 0) {
                int pos = (int) (position * 1.0 / duration * mBottomProgress.getMax());
                mBottomProgress.setProgress(pos);
            }
            int percent = mControlWrapper.getBufferedPercentage();
            if (percent >= 95) { //解决缓冲进度不能100%问题
                mBottomProgress.setSecondaryProgress(mBottomProgress.getMax());
            } else {
                mBottomProgress.setSecondaryProgress(percent * 10);
            }
        }
    }

    @Override
    public void onLockStateChanged(boolean isLocked) {
        onVisibilityChanged(!isLocked, null);
    }


}
